package com.rongxue.controller.payment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rongxue.mapper.SMobileCodeMapper;
import com.rongxue.mapper.SUserMapper;
import com.rongxue.pojo.ObjectResult;
import com.rongxue.pojo.SUser;
import com.rongxue.pojo.XMLBean;
import com.rongxue.service.BankBusinessService;
import com.rongxue.service.CashInAndOutService;
import com.rongxue.service.Impl.CashInAndOutServiceImpl;
import com.rongxue.service.shanbei.services.AccountService;
import com.rongxue.service.shanbei.util.ConfigUtil;
import com.rongxue.service.shanbei.util.SignUtil;
import com.rongxue.service.utils.MobileUtil;
import com.rongxue.service.utils.P2PMessageUtils;
import com.rongxue.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class CashInAndOutController {

    @Autowired
    private CashInAndOutService cashInAndOutService;

    @Autowired
    private BankBusinessService bankBusinessService;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Autowired
    private SMobileCodeMapper sMobileCodeMapper;

    @Autowired
    private SUserMapper sUserMapper;
    private static final Logger logger = LoggerFactory.getLogger(CashInAndOutController.class);


    /**
     * 定时任务
     */
    @Scheduled(cron = "0 30 0 * * ?")//每天零点30分执行
    //@Scheduled(cron="0/5 * *  * * ? ")
    public void taskInvestmentPayBack() {
        //清楚拦截的map
        CashInAndOutServiceImpl cashInAndOutService = new CashInAndOutServiceImpl();
        ConcurrentHashMap<String, Long> map = cashInAndOutService.map;
        map.clear();
        //清空短信
        sMobileCodeMapper.deleteMobileCode();
    }

    //充值
    @ResponseBody
    @RequestMapping(value = "/tender/recharge")
    public ObjectResult recharge(XMLBean xmlBean){
        if (xmlBean.getToken() == null || xmlBean.getToken().equals("") || xmlBean.getDevice_type() == null || xmlBean.getDevice_type().equals("")
                || xmlBean.getMoney() == null || xmlBean.getMoney().equals("")){
            return ObjectResult.build("0", "参数丢失,请重试");
        }
        ObjectResult objectResult = cashInAndOutService.recharge(xmlBean);

        return objectResult;
    }

    //用户提现
    @ResponseBody
    @RequestMapping(value = "/tender/withdraw_deposit")
    public ObjectResult withdrawDeposit(XMLBean xmlBean){
        if (xmlBean.getToken() == null || xmlBean.getToken().equals("") || xmlBean.getDevice_type()  == null || xmlBean.getDevice_type() .equals("")
                || xmlBean.getMoney() == null || xmlBean.getMoney().equals("")){
            return ObjectResult.build("0", "参数丢失,请重试");
        }
        ObjectResult objectResult = cashInAndOutService.withdrawDeposit(xmlBean);

        return objectResult;
    }

    //充值回调
    @ResponseBody
    @RequestMapping(value = "/tender/rechargeNotify", method = RequestMethod.POST, produces = "application/json")
    public void rechargeNotify() throws Exception {
        Map<String, Object> map = P2PMessageUtils.sign(request, "充值回调报文：");
        if (!(Boolean)map.get("flag"))return;

        ObjectResult ObjectResult = cashInAndOutService.verificationrechargeNotify((JSONObject)map.get("jsonObject"));
        if (ObjectResult.getCode().equals("0")){
            logger.info("msg:"+ObjectResult.getStr());
            return;
        }
        //返回回成功
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write("success");
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }

    }


    //提现回调
    @ResponseBody
    @RequestMapping(value = "/tender/withdraw_depositNotify")
    public void withdraw_depositNotify(XMLBean xmlBean, HttpServletResponse response) throws Exception {
        Map<String, Object> map = P2PMessageUtils.sign(request, "提现回调报文：");
        if (!(Boolean)map.get("flag"))return;

        ObjectResult ObjectResult = cashInAndOutService.withdraw_depositNotify((JSONObject)map.get("jsonObject"));

        if (ObjectResult.getCode().equals("0")){
            logger.info("msg:"+ObjectResult.getStr());
            return;
        }
        //返回回成功
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write("success");
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }
    }


    /**
     * 话费充值
     * @param xmlBean
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "/tender/telephonerateRecharge")
//    public ObjectResult telephonerateRecharge(XMLBean xmlBean){
//
//        if(!MobileUtil.isMobileNumber(xmlBean.getMobile())){
//            return ObjectResult.build("0","手机号格式不正确");
//        }
//
//        ObjectResult objectResult = cashInAndOutService.telephonerateRecharge(xmlBean);
//
//        return objectResult;
//    }


    /**
     * 充值话费列表
     * @param xmlBean
     * @return
     */
//    @ResponseBody
//    @RequestMapping(value = "/tender/telephonerate")
//    public ObjectResult telephonerate(XMLBean xmlBean){
//        String[][] array={{"10","9.99"},{"20","19.8"},{"30","29.5"},{"50","49"},
//                {"100","98"},{"200","196"},{"300","290"},{"500","480"}};
//
//        List<Map<String,String>> list = new ArrayList<>();
//
//        for (int i =0;i<array.length;i++){
//            Map<String,String> map = new HashMap<>();
//            map.put("real_value",array[i][0]);
//            map.put("value",array[i][1]);
//            list.add(map);
//        }
//
//        return ObjectResult.build("1","成功",list);
//    }

    /**
     * 存管密码修改
     * @param xmlBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tender/updataPassword")
    public ObjectResult updatapassword(XMLBean xmlBean){
        return cashInAndOutService.updatapassword(xmlBean);
    }

    /**
     * 存管密码修改回调
     * @param xmlBean
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/tender/updataPasswordNotify")
    public void updataPasswordNotify(XMLBean xmlBean) throws Exception {
        Map<String, Object> map = P2PMessageUtils.sign(request, "存管密码修改回调报文：");
        if (!(Boolean)map.get("flag"))return;

        //返回回成功
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write("success");
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }
    }

    /**
     * 网关重置密码查询
     * @param xmlBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tender/setPasswordQuery")
    public ObjectResult setPasswordQuery(XMLBean xmlBean)  {

        String str = null;
        Map<String, Object> reqMap = new HashMap<String, Object>();
        reqMap.put("service", "set_password_query");
        reqMap.put("order_id",xmlBean.getOrder_id());
        reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
        reqMap.put("fail_url", "http://apidata.rockfintech.com/doc/build/deposit.html");
        reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
        reqMap.put("sign_type", "");
        reqMap.put("encode", "UTF-8");
        reqMap.put("version", "2.0.0");
        reqMap.put("custom", "");
        reqMap.put("client", "000001");
        String rft_key = ConfigUtil.getPro("bank.key");
        String rft_secret = ConfigUtil.getPro("bank.secret");
        str = AccountService.createAccount(reqMap, rft_key, rft_secret);
        System.out.println(str.toString());
        JSONObject jsonObject = JSONObject.parseObject(str);

        return ObjectResult.build("1","成功",jsonObject);
    }

    /**
     *手续费签约
     * @param xmlBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tender/signBorrower")
    public ObjectResult signBorrower(XMLBean xmlBean){
        return cashInAndOutService.signBorrower(xmlBean);
    }

    @ResponseBody
    @RequestMapping(value = "/tender/signBorrowerNotify")
    public void signBorrowerNotify(XMLBean xmlBean) throws Exception {
        Map<String, Object> map = P2PMessageUtils.sign(request, "手续费签约回调报文：");
        if (!(Boolean)map.get("flag"))return;

        JSONObject jsonObject = (JSONObject) map.get("jsonObject");


        SUser resultUser =sUserMapper.selectUserInfoByOutSerialNo(jsonObject.getString("out_serial_no"));
        resultUser.setIs_sign(1);
        sUserMapper.updateByPrimaryKeySelective(resultUser);
        //返回回成功
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write("success");
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }
    }

    /**
     *手续费签约撤销
     * @param xmlBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tender/revokeRepayment")
    public ObjectResult revokeRepayment(XMLBean xmlBean){
        return cashInAndOutService.revokeRepayment(xmlBean);
    }


    /**
     * 签约累加
     * @param xmlBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tender/signAgain")
    public ObjectResult signAgain(XMLBean xmlBean){
        return cashInAndOutService.signAgain(xmlBean);
    }


    @ResponseBody
    @RequestMapping(value = "/tender/signAgainNotify")
    public void signAgainNotify(XMLBean xmlBean) throws Exception {
        Map<String, Object> map = P2PMessageUtils.sign(request, "签约累加回调报文：");
        if (!(Boolean)map.get("flag"))return;

        JSONObject jsonObject = (JSONObject) map.get("jsonObject");

//        SUser resultUser =sUserMapper.selectUserInfoByOutSerialNo(jsonObject.getString("out_serial_no"));
//        resultUser.setIs_sign(1);
//        sUserMapper.updateByPrimaryKeySelective(resultUser);
        //返回回成功
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write("success");
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }
    }
}

